package info.empathymobile.batterymonitorapp;

import info.empathymobile.monitor.EmpathyMonitorController;
import info.empathymobile.monitor.business.beans.MonitorEntry;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONException;

import android.content.Context;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.BatteryManager;

public class ServerSyncController {
	private EmpathyMonitorController monitorController = null;
	private ServerSyncBO serverSyncBO = new ServerSyncBO();
	private String userUUID;
	private String sync_auth_key;
	
	public ServerSyncController(Context context){
		this.monitorController = new EmpathyMonitorController(context);
		this.userUUID = new ServerSyncBO().getUserUUID(context);
		this.sync_auth_key = context.getString(R.string.empathy_sync_auth_key);
	}
	
	public void checkChargingAndConnectivityToSync(){
		MonitorEntry batteryEntry = monitorController.getBatteryStatus();
		MonitorEntry connectivityEntry = monitorController.getConnectivityStatus();
		
		if( batteryEntry.getStatus() == BatteryManager.BATTERY_STATUS_CHARGING
				&& connectivityEntry.getStatus() == MonitorEntry.CONNECTIVITY_ENTRY_NET_CONNECTED
				&& connectivityEntry.getType() == ConnectivityManager.TYPE_WIFI ){
					
			new ServerSyncThread().execute();
		}
	}
	
	private class ServerSyncThread extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			if(userUUID != null){
				ArrayList<Integer> successfulSyncIds = new ArrayList<Integer>();
				try {
					successfulSyncIds = 	serverSyncBO
											.syncWithEmpathyServer(
													monitorController.getAllMonitorEntries(), 
													userUUID, sync_auth_key
											);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
				monitorController.deleteMonitorEntriesById(successfulSyncIds);
			}
        	return true;
		}
	}
}
